import type { RouteRecordRaw } from 'vue-router'

function loaclLocalRoutes() {
  // 1.动态获取所有路由对象，放到数组中
  const localRouters: RouteRecordRaw[] = []
  // 1.1读取router/main中所有的ts文件
  const file: Record<string, any> = import.meta.glob('../router/main/**/*.ts', {
    eager: true // 立刻获取数据
  })
  // 1.2遍历获取文件中数据
  for (const key in file) {
    const module = file[key]
    localRouters.push(module.default)
  }
  return localRouters
}
// 存储菜单
export let firstMenu: any = null
export function mapMenusToRoutes(userMenus: any[]) {
  // 1.获取所有路由
  const localRouters = loaclLocalRoutes()
  // 2.根据菜单去匹配正确的路由
  const routes: RouteRecordRaw[] = []
  for (const menu of userMenus) {
    for (const submenu of menu.children) {
      const route = localRouters.find((item: any) => item.path === submenu.url)
      if (route) {
        // 1.给顶层菜单添加重定向,只添加一次
        if (!routes.find((item: any) => item.path === menu.url)) {
          routes.push({ path: menu.url, redirect: route.path })
        }
        // 2.给二级菜单添加路由
        routes.push(route)
      }

      // 记录第一次被匹配到的菜单
      if (firstMenu == null && route) firstMenu = submenu
    }
  }
  return routes
}

/**
 * 根据路径匹配需要显示的菜单
 * @param path  当前菜单路径
 * @param userMenus 所有菜单
 */
export const mapPathToMenu = (path: string, userMenus: any[]) => {
  for (const menu of userMenus) {
    for (const submenu of menu.children) {
      if (submenu.url === path) return submenu
    }
  }
  return null // 未找到匹配的菜单
}
/**
 * 获取当前菜单名及其父级菜单名
 * @param path 当前菜单路径
 * @param userMenus 所有菜单
 */
interface IBreacdcrumbs {
  name: string
  path: string
}
export const mapPathToBreadcrumbs = (path: string, userMenus: any[]) => {
  const breadcrumbs: IBreacdcrumbs[] = []
  for (const menu of userMenus) {
    for (const submenu of menu.children) {
      if (submenu.url === path) {
        breadcrumbs.push({ name: menu.name, path: menu.url })
        breadcrumbs.push({ name: submenu.name, path: submenu.url })
      }
    }
  }
  return breadcrumbs
}

/**
 * 菜单映射id列表
 * @param menuList 所有菜单
 */
export function mapMenuListToIds(menuList: any[]) {
  const ids: number[] = []
  function recurseGetId(menus: any[]) {
    for (const item of menus) {
      if (item.children) {
        recurseGetId(item.children)
      } else {
        ids.push(item.id)
      }
    }
  }
  recurseGetId(menuList)
  return ids
}

/**
 * 获取当前用户的所有按钮权限
 * @param menuList 菜单列表
 * @returns 权限数组
 */
export function mapMenusToPermissions(menuList: any[]) {
  const permissions: string[] = []
  function recurseGetPermission(menus: any[]) {
    for (const item of menus) {
      if (item.type === 3) {
        permissions.push(item.permission)
      } else {
        if (item.children) {
          recurseGetPermission(item.children)
        }
      }
    }
  }
  recurseGetPermission(menuList ?? [])
  return permissions
}
